package a51qindian.com.comprehensive.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.ChooseStaffAdapter;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.CountBaseModel;
import a51qindian.com.comprehensive.model.StaffInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/10/12 0012
 * Description: 选择员工界面 主要是分配任务时 选择员工
 */

public class ChooseStaffActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_staff)
    RecyclerView mRecyclerStaff;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;


    private List<StaffInfo> mStaffInfoList;
    private ChooseStaffAdapter mChooseStaffAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_staff;
    }

    @Override
    protected void initSth() {
        super.initSth();
        setSmartRefreshLayout(mLayoutRefresh);
        final String source = getIntent().getStringExtra("source");
        mTopNavigation.setNavigationBarListener(this);
        mStaffInfoList = new ArrayList<>();
        mRecyclerStaff.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerStaff.addItemDecoration(new LinearItemDecoration());
        mChooseStaffAdapter = new ChooseStaffAdapter(this);
        mRecyclerStaff.setAdapter(mChooseStaffAdapter);
        mChooseStaffAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int pos) {
                switch (source) {
                    case "apply":
                        final String did = getIntent().getStringExtra("did");
                        AlertDialog.Builder builder = new AlertDialog.Builder(ChooseStaffActivity.this)
                                .setTitle("提示")
                                .setMessage("是否将该任务分配给" + mStaffInfoList.get(pos).getRealname())
                                .setNegativeButton("取消", null)
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        apply(SpUtil.getUserInfo(ChooseStaffActivity.this, SpUtil.USER_ID), did, mStaffInfoList.get(pos).getUid());
                                    }
                                });
                        builder.create().show();
                        break;

                    case "repair":
                        final String rpId = getIntent().getStringExtra("rp_id");
                        AlertDialog.Builder repairBuilder = new AlertDialog.Builder(ChooseStaffActivity.this)
                                .setTitle("提示")
                                .setMessage("是否将该任务分配给" + mStaffInfoList.get(pos).getRealname())
                                .setNegativeButton("取消", null)
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        repair(SpUtil.getUserInfo(ChooseStaffActivity.this, SpUtil.USER_ID), rpId, mStaffInfoList.get(pos).getUid());
                                    }
                                });
                        repairBuilder.create().show();
                        break;

                    case "install":
                        StaffInfo info = mStaffInfoList.get(pos);
                        String staffId = info.getUid();
                        String staffName = info.getRealname();
                        Intent data = new Intent();
                        data.putExtra("staffId", staffId);
                        data.putExtra("staffName", staffName);
                        setResult(1, data);
                        finish();
                        break;
                }

            }
        });
        showStaffList(mUid,"0");
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showStaffList(mUid,"0");
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showStaffList(mUid,String.valueOf(mPage+1));
    }

    /**
     * 显示员工列表
     * @param uid   用户编号
     * @param page  页数
     */
    private void showStaffList(String uid,String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page",page);
        ObservableHelper.createObservable(RetrofitCreator.createService().staffList(map))
                .subscribe(new SelectorObserver<CountBaseModel<List<StaffInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(CountBaseModel<List<StaffInfo>> listBaseModel) {
                        List<StaffInfo> staffInfoList = listBaseModel.getData();
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage=0;
                            mStaffInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        }else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh&&staffInfoList.size()< Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mStaffInfoList.addAll(staffInfoList);
                        mChooseStaffAdapter.setStaffInfoList(mStaffInfoList);

                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showToast(e.getMessage());
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                    }
                });
    }

    /**
     * 分配订单
     *
     * @param uid     用户编号
     * @param did     订单编号
     * @param staffId 员工编号
     */
    private void apply(String uid, String did, String staffId) {
        mLayoutContent.onLoadingWithContent("正在分配");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("did", did);
        map.put("rp_id", staffId);
        ObservableHelper.createObservable(RetrofitCreator.createService().applyHandle(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            int code = object.getInt("code");
                            if (code != 1) {
                                showToast(object.getString("info"));
                                return;
                            }
                            showToast("分配成功");
                            setResult(RESULT_OK);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 分配维修任务
     * @param uid   用户编号
     * @param rpId  维修编号
     * @param opId  维修工编号
     */
    private void repair(String uid, String rpId, String opId) {
        mLayoutContent.onLoadingWithContent("正在分配");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("rp_id", rpId);
        map.put("op_id", opId);
        ObservableHelper.createObservable(RetrofitCreator.createService().repairHandle(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            int code = object.getInt("code");
                            if (code != 1) {
                                showToast(object.getString("info"));
                                return;
                            }
                            showToast("维修单分配成功");
                            setResult(RESULT_OK);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
